<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title}">实时监控面板</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .nav {
            background: rgba(255,255,255,0.95);
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        .nav a {
            color: #667eea;
            text-decoration: none;
            margin: 0 15px;
            font-weight: bold;
        }

        .nav a:hover {
            text-decoration: underline;
        }

        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .metric-card {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }

        .metric-value {
            font-size: 2.5em;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 10px;
        }

        .metric-label {
            color: #666;
            font-size: 1.1em;
        }

        .chart-container {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .activity-log {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            max-height: 400px;
            overflow-y: auto;
        }

        .log-item {
            padding: 10px;
            border-left: 4px solid #667eea;
            margin-bottom: 10px;
            background: #f9f9f9;
            border-radius: 5px;
        }

        .log-time {
            font-size: 0.8em;
            color: #888;
        }

        .log-message {
            margin-top: 5px;
            color: #333;
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-connected {
            background: #4CAF50;
        }

        .status-disconnected {
            background: #f44336;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 th:text="${title}">实时监控面板</h1>
            <p>SSE 集群监控与数据可视化</p>
        </div>

        <div class="nav">
            <a href="/">首页</a>
            <a href="/monitor">监控面板</a>
            <a href="/test">功能测试</a>
        </div>

        <!-- 关键指标 -->
        <div class="metrics-grid">
            <div class="metric-card">
                <div class="metric-value" id="activeConnections">0</div>
                <div class="metric-label">活跃连接数</div>
            </div>
            <div class="metric-card">
                <div class="metric-value" id="totalMessages">0</div>
                <div class="metric-label">总消息数</div>
            </div>
            <div class="metric-card">
                <div class="metric-value" id="clusterNodes">1</div>
                <div class="metric-label">集群节点数</div>
            </div>
            <div class="metric-card">
                <div class="metric-value" id="uptime">--</div>
                <div class="metric-label">运行时间</div>
            </div>
        </div>

        <!-- 连接状态图表 -->
        <div class="chart-container">
            <h3>连接数变化趋势</h3>
            <canvas id="connectionChart" width="800" height="200"></canvas>
        </div>

        <!-- 活动日志 -->
        <div class="activity-log">
            <h3>系统活动日志</h3>
            <div id="logContainer">
                <!-- 动态加载日志 -->
            </div>
        </div>
    </div>

    <script>
        let eventSource = null;
        let connectionCount = 0;
        let messageCount = 0;
        let startTime = Date.now();
        let chartData = [];

        // 初始化监控
        function initMonitoring() {
            connectSSE();
            updateMetrics();
            setInterval(updateMetrics, 1000);
            initChart();
        }

        // 连接SSE
        function connectSSE() {
            if (eventSource) {
                eventSource.close();
            }

            const clientId = 'monitor_' + Date.now();
            eventSource = new EventSource(`/api/sse/connect?clientId=${clientId}`);

            eventSource.onopen = function(event) {
                addLogMessage('监控面板已连接到SSE服务');
                updateConnectionStatus(true);
            };

            eventSource.onmessage = function(event) {
                messageCount++;
                try {
                    const data = JSON.parse(event.data);
                    addLogMessage(`收到消息: ${data.type} - ${data.message}`);
                } catch (e) {
                    addLogMessage(`收到消息: ${event.data}`);
                }
            };

            eventSource.onerror = function(event) {
                addLogMessage('SSE连接出现错误');
                updateConnectionStatus(false);
                
                setTimeout(() => {
                    if (eventSource.readyState === EventSource.CLOSED) {
                        addLogMessage('尝试重新连接...');
                        connectSSE();
                    }
                }, 5000);
            };

            // 监听自定义事件
            eventSource.addEventListener('heartbeat', function(event) {
                addLogMessage('心跳检测正常');
            });

            eventSource.addEventListener('user-action', function(event) {
                const data = JSON.parse(event.data);
                addLogMessage(`用户操作: ${data.message}`);
            });

            eventSource.addEventListener('system-notification', function(event) {
                const data = JSON.parse(event.data);
                addLogMessage(`系统通知: ${data.message}`);
            });
        }

        // 更新指标
        function updateMetrics() {
            // 更新运行时间
            const uptimeMs = Date.now() - startTime;
            const uptimeStr = formatUptime(uptimeMs);
            document.getElementById('uptime').textContent = uptimeStr;
            
            // 更新图表数据
            updateChart();
            
            // 请求服务器端数据
            fetch('/api/monitor/metrics')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('activeConnections').textContent = data.activeConnections || connectionCount;
                    document.getElementById('totalMessages').textContent = data.totalMessages || messageCount;
                    document.getElementById('clusterNodes').textContent = data.clusterNodes || 1;
                })
                .catch(error => {
                    console.log('获取服务器指标失败:', error.message);
                });
        }

        // 格式化运行时间
        function formatUptime(ms) {
            const seconds = Math.floor(ms / 1000);
            const minutes = Math.floor(seconds / 60);
            const hours = Math.floor(minutes / 60);
            
            if (hours > 0) {
                return `${hours}h ${minutes % 60}m`;
            } else if (minutes > 0) {
                return `${minutes}m ${seconds % 60}s`;
            } else {
                return `${seconds}s`;
            }
        }

        // 初始化图表
        function initChart() {
            const canvas = document.getElementById('connectionChart');
            const ctx = canvas.getContext('2d');
            
            // 简单的线图实现
            setInterval(() => {
                drawChart(ctx, canvas.width, canvas.height);
            }, 2000);
        }

        // 绘制图表
        function drawChart(ctx, width, height) {
            ctx.clearRect(0, 0, width, height);
            
            // 添加当前连接数据点
            const now = Date.now();
            chartData.push({
                time: now,
                connections: connectionCount
            });
            
            // 保持最近50个数据点
            if (chartData.length > 50) {
                chartData.shift();
            }
            
            if (chartData.length < 2) return;
            
            // 绘制网格
            ctx.strokeStyle = '#e0e0e0';
            ctx.lineWidth = 1;
            for (let i = 0; i <= 10; i++) {
                const y = (height / 10) * i;
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(width, y);
                ctx.stroke();
            }
            
            // 绘制连接数线条
            ctx.strokeStyle = '#667eea';
            ctx.lineWidth = 2;
            ctx.beginPath();
            
            const maxConnections = Math.max(...chartData.map(d => d.connections), 1);
            
            chartData.forEach((point, index) => {
                const x = (width / (chartData.length - 1)) * index;
                const y = height - (point.connections / maxConnections) * height;
                
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });
            
            ctx.stroke();
        }

        // 更新图表
        function updateChart() {
            // 模拟连接数变化
            if (eventSource && eventSource.readyState === EventSource.OPEN) {
                connectionCount = Math.max(1, connectionCount + Math.floor(Math.random() * 3) - 1);
            } else {
                connectionCount = 0;
            }
        }

        // 更新连接状态
        function updateConnectionStatus(connected) {
            // 可以在这里更新UI状态
        }

        // 添加日志消息
        function addLogMessage(message) {
            const logContainer = document.getElementById('logContainer');
            const logItem = document.createElement('div');
            logItem.className = 'log-item';
            
            const now = new Date();
            const timeStr = now.toLocaleTimeString();
            
            logItem.innerHTML = `
                <div class="log-time">${timeStr}</div>
                <div class="log-message">${message}</div>
            `;
            
            logContainer.insertBefore(logItem, logContainer.firstChild);
            
            // 保持最多20条日志
            while (logContainer.children.length > 20) {
                logContainer.removeChild(logContainer.lastChild);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(initMonitoring, 500);
        });

        // 页面卸载时清理
        window.addEventListener('beforeunload', function() {
            if (eventSource) {
                eventSource.close();
            }
        });
    </script>
</body>
</html>